<template>
  <div class="container">
    <!-- 分类导航栏 -->
    <div class="category-nav">
      <el-scrollbar>
        <div class="nav-wrapper">
          <el-radio-group
            v-model="categoryFilter"
            size="large"
            @change="handleFilter"
            class="category-group"
            >
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="main">主食</el-radio-button>
            <el-radio-button label="dessert">甜品</el-radio-button>
            <el-radio-button label="dish">菜品</el-radio-button>
            <el-radio-button label="drink">饮料</el-radio-button>
            <el-radio-button label="other">其他</el-radio-button>
          </el-radio-group>
        </div>
      </el-scrollbar>
    </div>

    <!-- 搜索区域 -->
    <div class="search-card">
      <el-input
        v-model="searchKey"
        placeholder="搜索菜品名称"
        class="search-input"
        clearable
        @keyup.enter="handleFilter"
        >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-card">
      <el-button type="primary" @click="openFormDialog('add')" class="add-btn">
        <el-icon><Plus /></el-icon>新增菜品
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-card">
      <el-table
        :data="paginatedData"
        border
        stripe
        style="width: 100%"
        height="calc(100vh - 260px)"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="50" align="center" fixed="left"/>
        <el-table-column type="index" label="序号" width="80" align="center" fixed="left"/>

        <el-table-column label="分类" width="120" align="center">
          <template #default="{row}">
            <el-tag
              :type="categoryMap[row.category].type"
              effect="light"
              class="category-tag"
              >
              {{ categoryMap[row.category].label }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="name"
          label="菜品名称"
          min-width="180"
          align="center"
          show-overflow-tooltip
          />

        <el-table-column label="价格" width="150" align="center">
          <template #default="{row}">
            <span class="price">¥{{ row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="图片" width="160" align="center">
          <template #default="{row}">
            <el-image
              class="food-image"
              :src="row.image"
              :preview-src-list="[row.image]"
              fit="cover"
              preview-teleported
              />
          </template>
        </el-table-column>

        <el-table-column
          prop="description"
          label="菜品描述"
          min-width="240"
          align="center"
          show-overflow-tooltip
          />

        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{row}">
            <el-button type="primary" size="small" @click="openFormDialog('edit', row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
            <el-button type="success" size="small" @click="openOrderDialog(row)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="card" v-if="pagination.total" style="display: flex; justify-content: flex-end;"> <!-- 类似布局 -->
      <el-pagination
        background
        :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next"
        :total="pagination.total"
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        />
    </div>

    <!-- 底部订单栏（合并后的版本） -->
    <div class="order-footer" v-if="selectedDishes.length > 0">
      <div class="order-summary">
        <el-button type="info" @click="cartVisible = true">
          <el-icon><ShoppingCart /></el-icon> 购物车({{ selectedDishes.length }})
        </el-button>
        <span class="total-price">总计：¥{{ totalPrice.toFixed(2) }}</span>
        <el-button type="primary" @click="confirmOrder">创建订单</el-button>
      </div>
    </div>

    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="cartVisible"
      title="购物车"
      :size="400"
      direction="rtl"
      >
      <el-scrollbar height="calc(100vh - 120px)">
        <div class="cart-list">
          <div v-for="(item, index) in selectedDishes" :key="item.id" class="cart-item">
            <div class="item-header">
              <span class="item-name">{{ item.name }}</span>
              <el-button
                type="danger"
                size="small"
                circle
                @click="removeFromCart(index)"
                >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>

            <div class="item-details">
              <el-input-number
                v-model="item.quantity"
                :min="1"
                :max="10"
                size="small"
                @change="updateQuantity(index, $event)"
                />

              <div class="specs-note">
                <span v-if="item.specs && item.specs.length" class="specs">规格：{{ item.specs.join(', ') }}</span>
                <span v-if="item.note" class="note">备注：{{ item.note }}</span>
              </div>
            </div>

            <div class="item-actions">
              <el-button
                type="primary"
                size="small"
                @click="openEditDialog(item, index)"
                >
                修改
              </el-button>
            </div>
            <el-divider />
          </div>
        </div>
      </el-scrollbar>
    </el-drawer>

    <!-- 购物车编辑对话框 -->
    <el-dialog v-model="editDialog.visible" :title="'修改 ' + editDialog.currentItem?.name" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="数量" required>
          <el-input-number
            v-model="editForm.quantity"
            :min="1"
            :max="10"
            controls-position="right"
            />
        </el-form-item>

        <el-form-item label="规格" v-if="showEditSpecs">
          <el-select
            v-model="editForm.specs"
            multiple
            placeholder="请选择规格"
            style="width: 100%"
            >
            <el-option
              v-for="item in specsOptions[editDialog.currentItem?.category]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="editForm.note"
            type="textarea"
            :rows="2"
            placeholder="请输入特殊要求"
            />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存修改</el-button>
      </template>
    </el-dialog>

    <!-- 订单确认对话框 -->
    <el-dialog v-model="orderDialog.visible" title="订单确认" width="700px">
      <el-table :data="selectedDishes" border>
        <el-table-column prop="name" label="菜品名称" width="180" />
        <el-table-column label="数量" width="100">
          <template #default="{row}">{{ row.quantity }}</template>
        </el-table-column>
        <el-table-column label="单价" width="120">
          <template #default="{row}">¥{{ row.price.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="specs" label="口味要求" width="180">
          <template #default="{row}">{{ row.specs && row.specs.length ? row.specs.join(', ') : '-' }}</template>
        </el-table-column>
        <el-table-column prop="note" label="备注" />
        <el-table-column label="小计" width="120">
          <template #default="{row}">¥{{ (row.price * row.quantity).toFixed(2) }}</template>
        </el-table-column>
      </el-table>

      <div class="dialog-footer">
        <span class="total-price">总计：¥{{ totalPrice.toFixed(2) }}</span>
        <el-button @click="orderDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitOrder">确认下单</el-button>
      </div>
    </el-dialog>

    <!-- 点餐对话框 -->
    <el-dialog v-model="dishDialog.visible" :title="'添加 ' + dishDialog.currentDish?.name" width="500px">
      <el-form :model="dishForm" label-width="80px">
        <el-form-item label="数量" required>
          <el-input-number
            v-model="dishForm.quantity"
            :min="1"
            :max="10"
            controls-position="right"
            />
        </el-form-item>

        <el-form-item label="口味" v-if="showSpecs">
          <el-select
            v-model="dishForm.specs"
            multiple
            placeholder="请选择口味"
            style="width: 100%"
            >
            <el-option
              v-for="item in specsOptions[dishDialog.currentDish?.category]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="dishForm.note"
            type="textarea"
            :rows="2"
            placeholder="请输入特殊要求"
            />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dishDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="addToOrder">确认添加</el-button>
      </template>
    </el-dialog>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="formDialog.visible"
      :title="formDialog.mode === 'add' ? '新增菜品' : '编辑菜品'"
      width="500px"
      >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="菜品分类" required>
          <el-select v-model="formData.category" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              />
          </el-select>
        </el-form-item>

        <el-form-item label="菜品名称" required>
          <el-input v-model="formData.name" />
        </el-form-item>

        <el-form-item label="价格" required>
          <el-input-number
            v-model="formData.price"
            :min="0"
            :precision="2"
            controls-position="right"
            />
        </el-form-item>

        <el-form-item label="菜品描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            />
        </el-form-item>

        <el-form-item label="图片URL">
          <el-input v-model="formData.image" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="formDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ShoppingCart, Delete, Search, Plus } from '@element-plus/icons-vue'

  const categoryMap = {
    main: { label: '主食', type: 'warning' },
    dessert: { label: '甜品', type: 'danger' },
    dish: { label: '菜品', type: 'success' },
    drink: { label: '饮料', type: 'primary' },
    other: { label: '其他', type: 'info' }
  }

  const specsOptions = {
    main: [
      { value: 'spicy', label: '加辣' },
      { value: 'mild', label: '微辣' },
      { value: 'no_spicy', label: '免辣' }
    ],
    dish: [
      { value: 'well_done', label: '全熟' },
      { value: 'medium', label: '七分熟' },
      { value: 'rare', label: '五分熟' }
    ],
    drink: [
      { value: 'normal_ice', label: '正常冰' },
      { value: 'less_ice', label: '少冰' },
      { value: 'hot', label: '热饮' }
    ]
  }

  const categoryOptions = [
    { value: 'main', label: '主食' },
    { value: 'dessert', label: '甜品' },
    { value: 'dish', label: '菜品' },
    { value: 'drink', label: '饮料' },
    { value: 'other', label: '其他' }
  ]

  const mockData = [
    {
      id: 1,
      category: 'main',
      name: '意大利肉酱面',
      price: 58.0,
      description: '经典番茄肉酱口味，手工制作面条',
      image: 'https://source.unsplash.com/random/200x200?pasta'
    },
    {
      id: 2,
      category: 'drink',
      name: '鲜榨橙汁',
      price: 25.0,
      description: '新鲜橙子现榨',
      image: 'https://source.unsplash.com/random/200x200?juice'
    }
  ]

  // 响应式数据
  const loading = ref(false)
  const searchKey = ref('')
  const categoryFilter = ref('')
  const tableData = ref([...mockData])
  const selectedDishes = ref([])
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: mockData.length
  })

  const formDialog = reactive({
    visible: false,
    mode: 'add'
  })

  const dishDialog = reactive({
    visible: false,
    currentDish: null
  })

  const orderDialog = reactive({
    visible: false
  })

  const cartVisible = ref(false)
  const editDialog = reactive({
    visible: false,
    currentItem: null,
    index: -1
  })

  const formData = reactive({
    id: null,
    category: 'main',
    name: '',
    price: 0,
    description: '',
    image: ''
  })

  const dishForm = reactive({
    quantity: 1,
    specs: [],
    note: ''
  })

  const editForm = reactive({
    quantity: 1,
    specs: [],
    note: ''
  })

  // 计算属性
  const filteredData = computed(() => {
    return tableData.value.filter(item => {
      const matchCategory = categoryFilter.value ?
        item.category === categoryFilter.value : true
      const matchSearch = item.name.toLowerCase()
        .includes(searchKey.value.toLowerCase())
      return matchCategory && matchSearch
    })
  })

  const paginatedData = computed(() => {
    const start = (pagination.current - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    return filteredData.value.slice(start, end)
  })

  const totalPrice = computed(() => {
    return selectedDishes.value.reduce((sum, item) => {
      return sum + (item.price * item.quantity)
    }, 0)
  })

  const showSpecs = computed(() => {
    const category = dishDialog.currentDish?.category
    return ['main', 'dish', 'drink'].includes(category)
  })

  const showEditSpecs = computed(() => {
    return ['main', 'dish', 'drink'].includes(editDialog.currentItem?.category)
  })

  // 方法
  const handleFilter = () => {
    loading.value = true
    setTimeout(() => loading.value = false, 300)
  }

  const handleSelectionChange = (selection) => {
    selectedDishes.value = selection
  }

  const openFormDialog = (mode, row) => {
    formDialog.mode = mode
    formDialog.visible = true
    if (mode === 'edit') {
      Object.assign(formData, row)
    } else {
      resetForm()
    }
  }

  const resetForm = () => {
    formData.id = null
    formData.category = 'main'
    formData.name = ''
    formData.price = 0
    formData.description = ''
    formData.image = ''
  }

  const submitForm = () => {
    if (!formData.name || !formData.category) {
      ElMessage.error('请填写必填项')
      return
    }

    if (formDialog.mode === 'add') {
      formData.id = Date.now()
      tableData.value.unshift({ ...formData })
      pagination.total++ // 更新总条数
    } else {
      const index = tableData.value.findIndex(item => item.id === formData.id)
      tableData.value.splice(index, 1, { ...formData })
    }

    ElMessage.success('操作成功')
    formDialog.visible = false
  }

  const handleDelete = (id) => {
    ElMessageBox.confirm('确认删除该菜品？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      tableData.value = tableData.value.filter(item => item.id !== id)
      pagination.total-- // 更新总条数
      ElMessage.success('删除成功')
    })
  }

  const openOrderDialog = (dish) => {
    dishDialog.currentDish = dish
    resetDishForm()
    dishDialog.visible = true
  }

  const resetDishForm = () => {
    dishForm.quantity = 1
    dishForm.specs = []
    dishForm.note = ''
  }

  const addToOrder = () => {
    const specsText = dishForm.specs.map(value =>
      specsOptions[dishDialog.currentDish.category]?.find(item => item.value === value)?.label || ''
                                        ).filter(label => label);

    selectedDishes.value.push({
      ...dishDialog.currentDish,
      quantity: dishForm.quantity,
      specs: specsText,
      note: dishForm.note
    })

    ElMessage.success('已添加到订单')
    dishDialog.visible = false
  }

  const confirmOrder = () => {
    orderDialog.visible = true
  }

  const submitOrder = () => {
    ElMessage.success('订单创建成功')
    orderDialog.visible = false
    selectedDishes.value = []
  }

  // 购物车相关方法
  const openEditDialog = (item, index) => {
    editDialog.currentItem = item
    editDialog.index = index
    editForm.quantity = item.quantity
    editForm.specs = item.specs || []
    editForm.note = item.note
    editDialog.visible = true
  }

  const saveEdit = () => {
    if (editDialog.index > -1) {
      selectedDishes.value[editDialog.index] = {
        ...selectedDishes.value[editDialog.index],
        ...editForm
      }
      ElMessage.success('修改成功')
      editDialog.visible = false
    }
  }

  const removeFromCart = (index) => {
    selectedDishes.value.splice(index, 1)
    ElMessage.success('已移除商品')
  }

  const updateQuantity = (index, value) => {
    selectedDishes.value[index].quantity = value
  }
</script>

<style scoped>
  .container {
    height: 100vh;
    padding: 16px;
    display: flex;
    flex-direction: column;
    background: #f5f7fa;
    box-sizing: border-box;
  }

  .category-nav {
    background: #fff;
    margin: -16px -16px 16px;
    box-shadow: 0 2px 12px rgba(0,0,0,.1);
  }

  .order-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    padding: 16px;
    box-shadow: 0 -2px 12px rgba(0,0,0,.1);
    z-index: 1000;
  }

  .order-summary {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 24px;
  }

  .total-price {
    font-size: 18px;
    color: #f56c6c;
    font-weight: 600;
  }

  .dialog-footer {
    margin-top: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .table-card .food-image {
    width: 120px;
    height: 90px;
    border-radius: 4px;
    border: 1px solid #eee;
  }

  .search-card {
    background: #fff;
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 12px;
    box-shadow: 0 1px 4px rgba(0,0,0,.08);
  }

  .pagination-card {
    background: #fff;
    padding: 12px 16px;
    border-radius: 8px;
    margin-top: 12px;
    box-shadow: 0 1px 4px rgba(0,0,0,.08);
  }

  .action-card {
    background: #fff;
    padding: 12px 16px;
    border-radius: 8px;
    margin-bottom: 12px;
    box-shadow: 0 1px 4px rgba(0,0,0,.08);
  }

  .category-tag {
    font-weight: 500;
    padding: 6px 12px;
    border-radius: 14px;
    transition: transform 0.2s;
  }

  .category-tag:hover {
    transform: scale(1.05);
  }

  .price {
    font-weight: 600;
    color: #f56c6c;
  }

  .cart-list {
    padding: 15px;
  }

  .cart-item {
    margin-bottom: 15px;
  }

  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .item-name {
    font-weight: 500;
    font-size: 16px;
  }

  .item-details {
    display: flex;
    gap: 15px;
    align-items: center;
    margin: 10px 0;
  }

  .specs-note {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 5px;
    font-size: 12px;
    color: #666;
  }

  .item-actions {
    text-align: right;
    margin-top: 10px;
  }

  :deep(.el-drawer__header) {
    margin-bottom: 0;
    padding: 20px;
    border-bottom: 1px solid #eee;
  }

  :deep(.el-drawer__body) {
    padding: 0;
  }
</style>